# -*- encoding: utf-8 -*-
# intentor parser
# like http://rygge.kommune.no/dllvis5.asp?id=1734
############################################################################
#    Copyright (C) 2007 by Håvard Gulldahl                                 #
#    havard@gulldahl.no                                                    #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

import logging, re, urlparse
import datetime
from time import strptime
import BeautifulSoup
import jeje.parser

RE_REG = re.compile(r'^.*Lnr:\ (\d+/\d+)\ Regdato:(\d{2}\.\d{2}\.\d{4})\ Arkivkode:([^$]+)$')
RE_SAK = re.compile(r'^Saksnr:\ ([^\ ]+)\ Dok.type:\ ([^\ ]+)\ Gradering:([^$]*)$')
RE_BEH = re.compile(r'^Saksb:\ ([^\s]+)\s+Journalenhet:\s?([^$]*)$')
RE_NAVN = re.compile(r'^Navn:\ ?([^$]*)$')
RE_DOK = re.compile(r'^Dok.beskr:\ ?([^$]*)$')
RE_TAG = re.compile(r'</?[^>]+>')

class parser(jeje.parser.ejeje_parser):
    def parse_enkeltjournal(self, suppe, uri):
        #jeje.parser.ejeje_parser.__init__(self, suppe, postjournal_samling)
        logging.info('starter intentor-parser')
        #dato = suppe.h1.string[len('Dagens postjournal '):]
        #logging.debug('fant dato %s', dato)
        #self.sett_info(dato)
        logging.debug('finner journaltabell i suppa')
        tabl = suppe.find('td', {'class':'normal', 'valign':'top', 'align':'left', 'width':'100%'})
        linjer = [l.strip() for l in unicode(tabl).replace('</p>', '<br />').split('<br />') if len(l.strip())>0 ]
        logging.debug('fant omtrent %d titler', len(linjer)/4)
        #u'Lnr: 5313/07 Regdato:04.10.2007 Arkivkode:040 H41 &amp;00',
        #u'Saksnr: 07/1136-1 Dok.type: /I Gradering:',
        #u'Saksb: PO/PO/RKRJK \r\nJournalenhet:SEN',
        #u'Navn: Ann Kirsti Backelin',
        #u'Dok.beskr: BEVITNELSE AV \r\nUNDERSKRIFT - KOMMUNENS REGLEMENT- OG RUTINEBESKRIVELSER',

        idx = 0
        post_idx = 1
        while idx < len(linjer):
            l = self.strp(linjer[idx])
            if not len(l) > 0 or l in (u'INNGÅENDE:', u'UTGÅENDE:'):
                idx += 1
                continue
            
            post = self.legg_til_post()
            
            try:
                lopenr, journaldato, arkivkode = RE_REG.match(self.strp(linjer[idx])).groups()
            except: 
                logging.error(self.strp(linjer[idx]))
                raise            
            try:
                saksnr, retning, gradering = RE_SAK.match(self.strp(linjer[idx+1])).groups()
            except: 
                logging.error(self.strp(linjer[idx+1]))
                raise            
            try:
                saksbehandler, enhet = RE_BEH.match(self.strp(linjer[idx+2])).groups()
            except: 
                logging.error(self.strp(linjer[idx+2]))
                raise            
            try:
                adressat = RE_NAVN.match(self.strp(linjer[idx+3])).group(1)
            except: 
                logging.error(self.strp(linjer[idx+3]))
                raise            
            try:
                tittel = RE_DOK.match(self.strp(linjer[idx+4])).group(1)
            except: 
                logging.error(self.strp(linjer[idx+4]))
                raise            

            logging.debug('arbeider med post #%d: %s', post_idx, tittel)

            post.sett_tittel(unicode(tittel))
            #post.sett_uri(_tittel['href'])
            
            if len(gradering)>0:
                post.sett_lovreferanse(unicode(gradering))
            post.sett_offentlig(len(gradering)>0)
            ##logging.debug('arkivsaksnr: %s, refnr: %s', _arkivsaksnr, _refnr)
            post.sett_adressat(unicode(adressat))
            person = post.sett_saksbehandler(unicode(saksbehandler))
            avdeling = person.sett_organisasjon(unicode(enhet))
            avdeling.type = u'avdeling'
            avdeling.moder_id = post.postjournal.organisasjon_id
            
            #person.sett_uri(_saksbehandler[0]['href'])
            post.sett_arkivdato(datetime.datetime(*strptime(journaldato, '%d.%m.%Y')[0:6]))
            #post.sett_sakskompleks = _sakskompleks.next
            _arkivsaksnr, _dokumentnr = saksnr.split('-')
            post.sett_arkivsaksnr(_arkivsaksnr)
            post.sett_dokumentnr(_dokumentnr)
            post.sett_refnr(unicode(lopenr))
            post.sett_retning(unicode(retning[1]))
            post.sett_kommentar(unicode('Arkivkode: %s' % arkivkode))
            post.kontroller_felter()
            idx += 5
            post_idx += 1
        return self.journalposter

    def finn_enkeltjournal_uri(self, postjournal, suppe, dato=None):
        if dato is None:
            return unicode(postjournal.enkeltjournal_uri), datetime.date.today()
        
        raise ParseError("Journal doesn't support fetching dates in the past")
    
    def strp(self, s):
        return RE_TAG.sub('', s).replace('\r\n','').strip()
